package com.demo.lock;

public class A {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ticket.increment();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                ticket.decrement();
            }
        },"B").start();
    }
}

//生产消费问题
//判断等待，业务，通知
class Ticket{
    private int num = 0;

    public synchronized void increment(){
        //使用while判断，而不使用if 防止更多线程下虚拟唤醒
        while (num!=0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"=>增加了："+num);
        this.notifyAll();
    }

    public synchronized void decrement(){
        while (num==0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"=>减少了："+num);
        this.notifyAll();
    }

}